extends NodeState


@export var barrel: Barrel


var velocity: Vector2 = Vector2.ZERO
var height: float = 0.0
var height_speed: float = 0.0


func _on_process(delta : float) -> void:
	barrel.position += velocity * delta
	process_air_time(delta)


func _on_physics_process(_delta : float) -> void:
	pass


func _on_next_transitions() -> void:
	pass


func _on_enter() -> void:
	barrel.sprite.frame = 1
	process_affected()

	EntityManager.spawn_collectible.emit(barrel.content_type,
										Knife.STATE_FALL,
										barrel.global_position,
										Vector2.ZERO,
										0.0,
										false)


func _on_exit() -> void:
	pass


func process_affected():
	var emit_direction := barrel.take_damage_emit_direction()
	if emit_direction == null:
		return
	var direction: Vector2 = Vector2.RIGHT if emit_direction.x > 0 else Vector2.LEFT
	velocity = direction * barrel.knockback_intensity

	height_speed = barrel.knockback_intensity * 2


func process_air_time(delta: float):
	barrel.sprite.position = Vector2.UP * height

	height += height_speed * delta
	if height < 0.0:
		height = 0.0
		barrel.queue_free()
	else:
		height_speed -= GlobalConstants.GRAVITY * delta

	# 下落时逐渐消失
	if height_speed < 0.0:
		barrel.modulate.a -= delta * barrel.dissipate_speed
